package me.lwn.auth.security.web.authentication.dao;

import me.lwn.auth.security.utils.LocalMessageSource;
import me.lwn.auth.security.web.authentication.BadSmsCodeException;
import me.lwn.auth.security.web.authentication.SmsAuthenticationToken;
import me.lwn.auth.security.web.authentication.SmsVerifyService;
import org.springframework.context.support.MessageSourceAccessor;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;

public class SmsAuthenticationProvider implements AuthenticationProvider {

    private final UserDetailsService userDetailsService;
    private final SmsVerifyService smsVerifyService;
    private final MessageSourceAccessor localMessageSource = LocalMessageSource.getAccessor();

    public SmsAuthenticationProvider(UserDetailsService userDetailsService, SmsVerifyService smsVerifyService) {
        this.userDetailsService = userDetailsService;
        this.smsVerifyService = smsVerifyService;
    }

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {

        SmsAuthenticationToken smsAuthenticationToken = (SmsAuthenticationToken) authentication;
        if (smsVerifyService.isInvalidLoginCode(smsAuthenticationToken.getMobile(), smsAuthenticationToken.getCode())) {
            throw new BadSmsCodeException(localMessageSource.getMessage("SmsAuthenticationProvider.badSmsCode", "Invalid sms code"));
        }
        UserDetails userDetails = userDetailsService.loadUserByUsername(authentication.getName());
        return new UsernamePasswordAuthenticationToken(userDetails.getUsername(), null, userDetails.getAuthorities());
    }

    @Override
    public boolean supports(Class<?> authentication) {
        return (SmsAuthenticationToken.class.isAssignableFrom(authentication));
    }
}
